angular.module('security.interceptor', ['security.retryQueue'])

// http interceptor 监听用户权限
.factory('securityInterceptor', ['$injector', 'securityRetryQueue', function($injector, queue) {
    return function(promise) {
        // Intercept failed requests
        return promise.then(null, function(originalResponse) {
            if(originalResponse.status === 401) { // 未登录状态
                // The request bounced because it was not authorized - add a new request to the retry queue
                promise = queue.pushRetryFn('unauthorized-server', function retryRequest() {
                    // We must use $injector to get the $http service to prevent circular dependency
                    return $injector.get('$http')(originalResponse.config);
                });
            }
            return promise;
        });
    };
}])

// 将自定义的interceptor添加到$httpProvider队列中
.config(['$httpProvider', function($httpProvider) {
    $httpProvider.responseInterceptors.push('securityInterceptor');
}]);

